﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections;
using System.ComponentModel.Design;

namespace System
{
    public static class ReflectionExt
    {
        /// <summary>
        /// Gets value of property from an object (calls PropertyInfo.GetValue(target, null))
        /// </summary>
        /// <param name="propertyInfo"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        public static object GetValue(this PropertyInfo propertyInfo, object target)
        {
            return propertyInfo.GetValue(target, null);
        }

        /// <summary>
        /// Searches for type
        /// </summary>
        /// <param name="provider">IServiceProvider</param>
        /// <param name="typeFullName">Type Full Name</param>
        /// <param name="baseType">Base Type if null then is set to typeof(object) </param>
        /// <param name="excludeGlobalTypes">Exclude Global Types</param>
        /// <returns></returns>
        public static Type GetType(this IServiceProvider provider, string typeFullName, Type baseType, bool excludeGlobalTypes = true)
        {
            if (provider != null)
            {
                try
                {
                    if (baseType == null)
                        baseType = typeof(object);
                    ICollection colTp = ((ITypeDiscoveryService)provider.GetService(typeof(ITypeDiscoveryService))).GetTypes(baseType, excludeGlobalTypes);
                    if (colTp != null)
                    {
                        foreach (Type t in colTp)
                        {
                            if (t.FullName == typeFullName)
                                return t;
                        }
                    }
                }
                catch { }
            }
            return null;
        }

        public static ICollection GetTypes(this IServiceProvider provider, Type baseType, bool excludeGlobalTypes = true)
        {
            if (provider != null)
            {
                try
                {
                    if (baseType == null)
                        baseType = typeof(object);
                    ICollection colTp = ((ITypeDiscoveryService)provider.GetService(typeof(ITypeDiscoveryService))).GetTypes(baseType, excludeGlobalTypes);
                    return colTp;
                }
                catch { }
            }
            return null;
        }
    }
}
